<template>
   
            <div class="sys-page" >
                <!-- <app-title :title="dialogTitle" style="display:inline;"></app-title> -->

                 <el-button type="success" size="mini" @click="refresh()" round style=" margin-top:10px;" icon="el-icon-refresh">刷新</el-button>

                <el-button type="info" size="mini" @click="download()" round style="margin-top:10px;margin-bottom:10px;" icon="el-icon-download">导出</el-button>
                <!-- <app-notes> -->
                    <!-- <el-button @click="searchFlag = true">登录日志报表统计分析</el-button> -->
                    <el-collapse accordion>
                      <el-collapse-item >
                        <template slot="title">
                          <span style="font-size:20px;color:orange;">统计分析</span><i class="header-icon el-icon-search"></i>
                        </template>
                        <el-form :model="form" :label-width="formLabelWidth">
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="用户:" >
                                    <el-input v-model="form.userId" placeholder="请输入用户名"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="终端:"  :label-width="formLabelWidth" >
                                    <el-input v-model="form.source" placeholder="请输入终端IP"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="事件" :label-width="formLabelWidth">
                                    <el-select v-model="form.event" placeholder="请选择事件类型">
                                        <el-option label="LOGININ" value="LOGININ"></el-option>
                                        <el-option label="LOGINOUT" value="LOGINOUT"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="结果" :label-width="formLabelWidth">
                                    <el-select v-model="form.result" placeholder="请选择活动区域">
                                        <el-option label="成功" value="0"></el-option>
                                        <el-option label="失败" value="1"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <!-- <el-col :span="6">
                                <el-form-item label="数据完整状态" :label-width="formLabelWidth">
                                    <el-select v-model="form.result" placeholder="请选择活动区域">
                                        <el-option label="完整" value="0"></el-option>
                                        <el-option label="篡改" value="1"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col> -->
                            <el-col :span="9">
                                <el-form-item label="起始时间" :label-width="formLabelWidth">
                                        <el-date-picker type="datetime" placeholder="选择时间" v-model="form.stime" @change="getSTime"  value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;"></el-date-picker>

                                </el-form-item>
                            </el-col>
                            <el-col :span="9">
                                <el-form-item label="结束时间" :label-width="formLabelWidth">
                                    <el-date-picker type="datetime" placeholder="选择时间" v-model="form.etime" @change="getETime" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;"></el-date-picker>

                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                                <el-button icon="el-icon-delete" @click="reset">清空</el-button>
                                <el-button type="primary" icon="el-icon-search" @click="conditionQuery">查询</el-button>
                            </el-row>
                    </el-form>

                      </el-collapse-item>   
                    </el-collapse>
                   
                <!-- </app-notes> -->
                   
                    <el-table v-loading="loading"  :data="tableData.body" >
                        <el-table-column type="expand">
                          <template slot-scope="props">
                            <el-form label-position="left" inline class="demo-table-expand">
                              <el-form-item label="操作时间" >
                                <span>{{ timeFormatter(props.row, null, null) }}</span>
                              </el-form-item>
                              <el-form-item label="触发用户">
                                <span>{{ props.row.userId }}</span>
                              </el-form-item>
                              <el-form-item label="事件">
                                <span>{{ props.row.event}}</span>
                              </el-form-item>
                              <el-form-item label="终端IP">
                                <span>{{ props.row.source }}</span>
                              </el-form-item>
                              <el-form-item label="类型">
                                <span>{{ typeFormatter(props.row, null, null) }}</span>
                              </el-form-item>
                              <el-form-item label="结果">
                                <span>{{ resultFormatter(props.row, null, null) }}</span>
                              </el-form-item>
                              <el-form-item label="描述" style="margin-right: 0; margin-bottom: 0; width:100%;">
                                <span style="color:red;">{{ props.row.desc }}</span>
                              </el-form-item>
                            </el-form>
                          </template>
                        </el-table-column>


                         <el-table-column style="background-color:16#123456" label="数据安全" width="120" align="center">
                           <template slot-scope="scope">
                                <div v-if="scope.row.safe==false">
                                    <i class="el-icon-warning"></i>
                                    <span style="color:red"> 数据异常</span>
                                </div>
                                <div v-else-if="scope.row.safe==true">
                                    <i class="el-icon-success"></i>
                                    <span style="color:green">数据完整</span>
                                </div>
                          </template>
                        </el-table-column>
                         <el-table-column label="操作时间" align="center" width="180" prop="time" :formatter="timeFormatter">
                        </el-table-column>
                        <el-table-column label="触发用户" align="center" width="120" prop="userId"></el-table-column>
                        <el-table-column label="事件"  align="center" width="130" prop="event">
                        </el-table-column>

                        <el-table-column label="终端IP"  align="center" width="180" prop="source"></el-table-column>
                        <el-table-column label="类型" align="center" width="120" prop="type" :formatter="typeFormatter"></el-table-column>
                        <el-table-column label="结果" align="center"  prop="result" :formatter="resultFormatter">
                            <template slot-scope="scope">
                                <div v-if="scope.row.result==0">
                                    成功
                                </div>
                                <div v-else-if="scope.row.result!=0">
                                    <i class="el-icon-warning"></i>
                                    <span style="color:red">失败</span>
                                </div>
                          </template>
                        </el-table-column>
                       <!--  <el-table-column label="描述" align="center" width="220" prop="desc"></el-table-column> -->
                       
                    </el-table>
                <div align="center">
                      <el-pagination
                          @size-change="handleSizeChange"
                          @current-change="handleCurrentChange"
                          :current-page="currentPage"
                          :page-sizes="[10, 20, 30, 40]"
                          :page-size="pageSize"
                          layout="total, sizes, prev, pager, next, jumper"
                          :total="totalCount">
                      </el-pagination>
                  </div>
                  <!-- dialog title="用户登陆频率统计" > -->
                    <div class="sys-page">
                        <app-section title="用户登陆频率排名统计">
                           <!--  <app-toolbar>
                                <el-button type="primary" @click="getChartData">刷新数据</el-button>
                            </app-toolbar> -->
                            <div id="myChart" :style="{width: '600px', height: '500px'}"></div>
                        </app-section>
                    </div>
                <!-- </el-dialog> -->
            </div>
       


</template>

<style>
  .el-table .warning-row {
    background: #F08080;
  }

  .el-table .success-row {
    background:#f0f9eb;
  }
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 130px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 33%;
  }
</style>

<script>
// import ElButton from "element-ui/packages/button/src/button";
import mEcharts from 'echarts'

export default {
    // components: {ElButton},
    name: 'loginlog',
    data(){
        return {
            dialogTitle:"用户登录日志查询",
            chartsobj:null,
            searchFlag: true,
            currentPage: 1,
            dataCount: null,
            dialogVisible: false,
            pageNum: 1,
            dataCount: null,
            totalCount: 0,
            pageSize: 10,
            currentPage: 1,
            start: 1,
            loading: false,
            url: window.axios_g.BASEURL,
            reportPermission: false,
            tableData:{
                body:[],
                head:[],
                loading : true
            },
            echartList: [],

            exportCondition: {
                result: null,
                userId: null,
                source: null,
                stime: null,
                etime: null
            },
            form: {
                result: null,
                userId: null,
                event: null,
                source: null,
                stime: null,
                etime: null
            },
            formLabelWidth: '120px',
            errorMsg:"您的信息有误，请联系管理员修改",
            reliable:true,

       }
    },
    mounted(){
        this.query()
        this.exportCondition.result=null
        this.exportCondition.userId=null
        this.exportCondition.source=null
        this.exportCondition.stime=null
        this.exportCondition.etime=null
        this.$nextTick(function() {
            // this.showReport()
          
          })
    },
    methods:{
        showReport(){
             let msg = {
            result: this.form.result,
            event: this.form.event,
            source:this.form.source,
            userId: this.form.userId,
            stime: this.timeStrToTimestamp(this.form.stime),
            etime: this.timeStrToTimestamp(this.form.etime)
          }
            let url = "/login-logger/findreportechart.shtml";
            this.HTTP.methods.apiGet(url,msg).then(res =>
            {
                if(res.code == 200){
                    if(res.data){
                        this.echartList = []
                        for(let i=0; i<res.data.length; i++){
                            let obj = {value:res.data[i].nums,
                                    name: res.data[i].userId}
                            this.echartList.push(obj)
                        }
                    }
                    console.log(this.echartList)
                    this.drawPie('myChart')
                }
            })
        },
        drawPie(obj){
            /*ECharts图表*/
         var myChart = mEcharts.init(document.getElementById(obj));
         myChart.setOption({
          series : [
           {
            name: '用户登陆频率统计',
            type: 'pie',
            radius: '50%',
            itemStyle:{ 
              normal:{ 
                    label:{ 
                      show: true, 
                      formatter: '{b} : {c} ({d}%)' 
                    }, 
                    labelLine :{show:true} 
                  } 
              } ,
            data:this.echartList
           }
          ]
         })
        },
         checkData(){
            this.HTTP.methods.apiGet("/login-logger/safe.shtml").then(res =>
            {
               if(res.data == false){
                    
                    this.$notify({
                      title: '警告',
                      message: '您访问的这张表数据不完整，记录被删除过'
                    });
               }

            }
        )
        },
        download(){
            var param_s = encodeURI(JSON.stringify(this.exportCondition))
            let base = this.url
            let downloadUrl = "login-logger/export.shtml?entity=" + param_s
            
            let data = {}
           
            var link = document.createElement('a')
            link.href = base + downloadUrl
            console.log(link.href)
            link.download = '登录日志导出表.xls'
            link.click()
           
        },
         reset() {
            this.reportPermission = false;
            this.form.result=null
            this.form.userId=null
            this.form.event=null
            this.form.source=null
            this.form.kernel=null
            this.form.normal=null
            this.form.stime=null
            this.form.etime=null

            this.exportCondition.result=null
            this.exportCondition.userId=null
            this.exportCondition.event=null
            this.exportCondition.source=null
            this.exportCondition.kernel=null
            this.exportCondition.normal=null
            this.exportCondition.stime=null
            this.exportCondition.etime=null
        },
        //每页显示数据量变更
        handleSizeChange: function(val) {
            this.pageSize = val;
             if(this.reportPermission){
                this.conditionQuery()
            }else{
                this.query()
            }
        },

        //页码变更
        handleCurrentChange: function(val) {
            this.pageNum = val;
             if(this.reportPermission){
                this.conditionQuery()
            }else{
                this.query()
            }
        },
        refresh(){
             if(this.reportPermission){
                this.conditionQuery()
            }else{
                this.query()
            }
            
        },
        getSTime: function (val) {
            this.form.stime = val;
        },
        getETime: function (val) {
            this.form.etime = val;
        },
        timeFormatter: function (row, colum, cellValue) {
            return this.formatDateTime(row.time);
        },
        resultFormatter : function (row, column, cellValue) {
            return row.result == "0"? "成功": "失败";
        },
        typeFormatter: function(row, column, cellValue) {
            return "0" == row.type ? "登录": "登出";
        },
        tableRowClassName({row, rowIndex}) {
          if(this.reliable === false){
            return 'warning-row';
          }else{
              return 'success-row'
          }
        },
        formatDateTime: function(inputTime){
            var date = new Date(inputTime);
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            m = m < 10 ? ('0' + m) : m;
            var d = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            var h = date.getHours();
            h = h < 10 ? ('0' + h) : h;
            var minute = date.getMinutes();
            var second = date.getSeconds();
            minute = minute < 10 ? ('0' + minute) : minute;
            second = second < 10 ? ('0' + second) : second;
            return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
        },
        timeStrToTimestamp: function (str) {
            if(str){
                str = str.substring(0,19);
                str = str.replace(/-/g,'/');
                return new Date(str).getTime();
            }
            return null;
        },
        conditionQuery: function () {
          
          let msg = {
            result: this.form.result,
            event: this.form.event,
            source:this.form.source,
            userId: this.form.userId,
            stime: this.timeStrToTimestamp(this.form.stime),
            etime: this.timeStrToTimestamp(this.form.etime)
          }
        
            let url = "/login-logger/findreport.shtml?pageSize="+this.pageSize+
                "&pageNum="+this.pageNum+"&entity="+encodeURI(JSON.stringify(msg));
            // url = url+"pageSize="+this.pageSize+"&";
            // url = url+"pageNum="+this.pageNum+"&";
            // url = (this.form.result == null || this.form.result == '') ? url: url+"result="+this.form.result+"&";
            // url = (this.form.event == null || this.form.event == '') ? url: url+"event="+this.form.event+"&";
            // url = (this.form.source == null || this.form.source == '') ? url: url+"source="+this.form.source+"&";
            // url = (this.form.userId == null || this.form.userId == '') ? url: url+"userId="+this.form.userId+"&";
            // url = (this.form.stime == null || this.form.stime == '') ? url: url+"stime="+this.timeStrToTimestamp(this.form.stime)+"&";
            // url = (this.form.etime == null || this.form.etime == '') ? url: url+"etime="+this.timeStrToTimestamp(this.form.etime)+"&";
            // url = this.form.result == null ? url: url+"result="+this.form.result+"&";
            this.HTTP.methods.apiGet(url).then(res =>
            {
                //console.log(res)
                this.searchFlag = false;
                this.loading = true;
                if(null != res && 200 == res.code){

                 this.tableData.body = res.data.list
                 this.totalCount = res.data.total
                this.loading = false
                this.reportPermission = true

                 this.exportCondition.result=this.form.result
                this.exportCondition.userId=this.form.userId
                this.exportCondition.source=this.form.source
                this.exportCondition.stime=this.form.stime
                this.exportCondition.etime=this.form.etime
                this.showReport()
                this.checkData()
            }else{
                 this.tableData.body = []
                this.loading = false
                 this.totalCount =0 
                 this.reportPermission = false
            }
        }).catch(err => {
                    this.$message.error('网络超时')
                    this.loading = false
                     this.totalCount = 0
                     this.tableData.body = []
                      this.reportPermission = false
                })
        },
        query(){
                let msg = {
                    pageSize: this.pageSize,
                    pageNum: this.pageNum
                }
                this.HTTP.methods.apiGet("/login-logger/page.shtml?pageSize="+this.pageSize+"&pageNum="+this.pageNum).then(res =>
                {
                    if(null != res && 200 == res.code ){

                        this.tableData.body = res.data.rows
                       this.totalCount = res.data.total
                        this.loading = false
                        this.showReport()
                        this.checkData()
                    }else{
                        this.tableData.body = null
                        this.loading = false
                         this.totalCount = 0
                    }
                }).catch(err => {
                        this.$message.error('网络超时')
                        this.loading = false
                        this.totalCount = 0
                    })
        }
    },
    created() {
        this.query()
    }
}
</script>


